﻿' (c) Copyright Microsoft Corporation.
' This source is subject to the Microsoft Public License (Ms-PL).
' Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
' All other rights reserved. 

' get past MouseData not being initialized warning...it needs to be there for p/invoke
'INSTANT VB TODO TASK: There is no equivalent to #pragma directives in VB:
'#pragma warning disable 0649

Imports System.ComponentModel
Imports System.Runtime.InteropServices

Namespace Microsoft.Kinect.Samples.CursorControl
	Friend Structure MouseInput
		Public X As Integer
		Public Y As Integer
		Public MouseData As UInteger
		Public Flags As UInteger
		Public Time As UInteger
		Public ExtraInfo As IntPtr
	End Structure

	Friend Structure Input
		Public Type As Integer
		Public MouseInput As MouseInput
	End Structure

	Public NotInheritable Class NativeMethods

		Private Sub New()
		End Sub
		Public Const InputMouse As Integer = 0

		Public Const MouseEventMove As Integer = &H1
		Public Const MouseEventLeftDown As Integer = &H2
		Public Const MouseEventLeftUp As Integer = &H4
		Public Const MouseEventRightDown As Integer = &H8
		Public Const MouseEventRightUp As Integer = &H10
		Public Const MouseEventAbsolute As Integer = &H8000

		Private Shared lastLeftDown As Boolean

		<DllImport("user32.dll", SetLastError := True)> _
		Private Shared Function SendInput(ByVal numInputs As UInteger, ByVal inputs() As Input, ByVal size As Integer) As UInteger
		End Function

		Public Shared Sub SendMouseInput(ByVal positionX As Integer, ByVal positionY As Integer, ByVal maxX As Integer, ByVal maxY As Integer, ByVal leftDown As Boolean)
			If positionX > Integer.MaxValue Then
				Throw New ArgumentOutOfRangeException("positionX")
			End If
			If positionY > Integer.MaxValue Then
				Throw New ArgumentOutOfRangeException("positionY")
			End If

			Dim i(1) As Input

			' move the mouse to the position specified
			i(0) = New Input()
			i(0).Type = InputMouse
			i(0).MouseInput.X = (positionX * 65535) \ maxX
			i(0).MouseInput.Y = (positionY * 65535) \ maxY
			i(0).MouseInput.Flags = MouseEventAbsolute Or MouseEventMove

			' determine if we need to send a mouse down or mouse up event
			If (Not lastLeftDown) AndAlso leftDown Then
				i(1) = New Input()
				i(1).Type = InputMouse
				i(1).MouseInput.Flags = MouseEventLeftDown
			ElseIf lastLeftDown AndAlso (Not leftDown) Then
				i(1) = New Input()
				i(1).Type = InputMouse
				i(1).MouseInput.Flags = MouseEventLeftUp
			End If

			lastLeftDown = leftDown

			' send it off
			Dim result As UInteger = SendInput(2, i, Marshal.SizeOf(i(0)))
			If result = 0 Then
				Throw New Win32Exception(Marshal.GetLastWin32Error())
			End If
		End Sub
	End Class
End Namespace
